<?php

namespace App\Models\Content;

use App\Models\Admin\Admin;
use App\Models\Model;
use Database\Factories\ArticleFactory;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;

class Article extends Model implements Sortable
{
	use HasDateTimeFormatter;
    use SoftDeletes;
    use SortableTrait;

    protected $fillable = [
        "key","category_id","title","picture","content","sort","state","views","likes","seo","publish_at","admin_id"
    ];

    public function category()
    {
        return $this->hasOne(ArticleCategory::class,"id","category_id");
    }

    public function admin()
    {
        return $this->hasOne(Admin::class,"id","admin_id");
    }

    public static function selectOptions()
    {
        return ["-1"=>"下线","0"=>"草稿","1"=>"发布"];
    }

    protected static function boot()
    {
        parent::boot();

        static::saving(function (Article $model){
            if ($model->state == 1){
                $model->publish_at = date("Y-m-d H:i:s");
            }
        });
    }

    public function getPictureUrl()
    {
        return sprintf("%s%s",config("app.asset_url"),$this->picture[0] == "/" ? $this->picture : "/".$this->picture);
    }

    public function determineOrderColumnName(): string
    {
        return "sort";
    }

    protected static function newFactory()
    {
        return new ArticleFactory;
    }

}
